<template>
  <el-card class="box-card">
    <h2 class="title">商品信息</h2>
    <el-form
      ref="productFormRef"
      :rules="rules"
      :model="productForm"
      label-width="80px"
    >
      <el-row>
        <el-col :span="colSize" :offset="offsetSize">
          <el-input type="hidden" v-model="productForm.id"></el-input>
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="productForm.name"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="9" :offset="offsetSize">
          <el-form-item label="商品分类" prop="typeId">
            <el-cascader
              class="typeCascader"
              @change="handleCateChange"
              v-model="productCateValue"
              :options="productCateOptions"
              :props="{ expandTrigger: 'hover', label: 'name', value: 'id' }"
              :placeholder="TypePlaceholder"
            >
            </el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="商品品牌" prop="brandId">
            <el-select
              v-model="productForm.brandId"
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in productBrandList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="colSize" :offset="offsetSize">
          <el-form-item label="商品描述" prop="detail">
            <el-input
              type="textarea"
              :autosize="{ minRows: 2 }"
              placeholder="请输入内容"
              v-model="productForm.detail"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="colSize" :offset="offsetSize">
          <el-form-item label="商品售价" prop="price">
            <el-input
              v-model="productForm.price"
              onkeyup="this.value = this.value.replace(/[^\d.]/g,'')"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="colSize" :offset="offsetSize">
          <el-form-item label="商品库存" prop="stock">
            <el-input
              v-model="productForm.stock"
              onkeyup="this.value = this.value.replace(/[^\d]/g,'')"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="9" :offset="offsetSize">
          <el-form-item label="是否上架" prop="isOnSale">
            <el-select v-model="productForm.isOnSale" placeholder="请选择">
              <el-option
                v-for="item in publishStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="是否上新" prop="isNew">
            <el-select v-model="productForm.isNew" placeholder="请选择">
              <el-option
                v-for="item in publishNewOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="colSize" :offset="offsetSize">
          <el-form-item label="商品图片" prop="file">
            <!--action-上传的地址,on-success的钩子可以接受后台返回结果-->
            <el-upload
              v-if="handleType !== 'view'"
              class="avatar-uploader"
              action="http://localhost:8081/upload/pic"
              name="file"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleSuccess"
              :before-upload="beforeUpload"
            >
              <img v-if="imageUrl" :src="baseUrl+imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <div slot="tip" class="el-upload__tip">
                请上传比例为1:1的图片以确保显示时不被压缩。
              </div>
            </el-upload>
            <el-image
              v-if="handleType === 'view'"
              style="height: 150px;width: 150px"
              :src="baseUrl+productForm.file"
            >
            </el-image>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="handleType !== 'view'">
        <el-col :span="colSize" :offset="8">
          <el-form-item>
            <el-button type="primary" @click="onSubmit">提 交</el-button>
            <el-button @click="onCancel">取 消</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="handleType === 'view'">
        <el-col :span="colSize" :offset="9">
          <el-form-item>
            <el-button type="primary" @click="onCancel">返 回</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
</template>

<script>
import { api_listWithChildren } from '../../api/productCate'
import { api_allBrandList } from '../../api/brand'
import { api_saveProduct } from '../../api/product'
import { api_productInfo } from '../../api/product'
export default {
  data() {
    return {
      handleType: 'add',
      TypePlaceholder: '请选择',
      colSize: 18,
      offsetSize: 3,
      productForm: {
        id: null,
        name: null,
        typeId: null,
        typeName: null,
        brandId: null,
        detail: null,
        price: null,
        stock: 0,
        isNew: null,
        isOnSale: null,
        file: null,
      },
      rules: {
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        typeId: [
          { required: true, message: '请选择商品分类', trigger: 'blur' },
        ],
        brandId: [
          { required: true, message: '请选择商品品牌', trigger: 'blur' },
        ],
        detail: [
          { required: true, message: '请输入商品描述', trigger: 'blur' },
        ],
        price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        isNew: [
          { required: true, message: '请选择商品是否上新', trigger: 'blur' },
        ],
        isOnSale: [
          { required: true, message: '请选择商品是否上架', trigger: 'blur' },
        ],
      },
      productBrandList: [],
      productCateValue: [],
      productCateOptions: [],
      publishStatusOptions: [
        {
          value: 1,
          label: '上架',
        },
        {
          value: 0,
          label: '下架',
        },
      ],
      publishNewOptions: [
        {
          value: 1,
          label: '是',
        },
        {
          value: 0,
          label: '否',
        },
      ],
      fileList: [],
      imageUrl: '',
      baseUrl: 'http://localhost:88/upload/',
    }
  },
  created() {
    this.handleProductCate()
    this.handleProductBrandList()
    this.getHandleType()
  },
  mounted() {
    this.getInfo()
  },
  computed: {
    headers() {
      return {
        Authorization: window.sessionStorage.getItem('token'),
      }
    },
  },
  methods: {
    async getInfo() {
      let id = this.$route.query.id
      if (id) {
        const { data: res } = await api_productInfo({
          id: id,
        })
        this.productForm = res.data
        this.productCateValue.push(res.data.parentType)
        this.productCateValue.push(res.data.typeId)
        this.TypePlaceholder = res.data.parentName + '/' + res.data.typeName
        this.imageUrl = res.data.file
      }
    },
    getHandleType() {
      this.handleType = this.$route.query.handleType
    },
    handleCateChange() {},
    //获取商品分类
    async handleProductCate() {
      const { data: res } = await api_listWithChildren()
      this.productCateOptions = res.data
    },
    //获取商品品牌
    async handleProductBrandList() {
      const { data: res } = await api_allBrandList()
      this.productBrandList = res.data
    },
    handleSuccess(res, file) {
      console.log(res)
      console.log(file)
      if (!res.success) {
        this.$message.error(res.msg)
        return
      }
      this.$message({
        message: res.msg,
        type: 'success',
      })
      this.imageUrl = this.baseUrl + res.data
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 5

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return (isJPG || isPNG) && isLt2M
    },
    onSubmit() {
      this.productForm.typeId = this.productCateValue[1]
        ? this.productCateValue[1]
        : null
      this.productForm.file = this.imageUrl
      this.$refs.productFormRef.validate(async (valid) => {
        if (!valid) {
          return false
        }
        const { data: res } = await api_saveProduct(this.productForm)
        if (!res.success) {
          this.$message.error(res.msg)
          return
        }
        this.$message({
          message: res.msg,
          type: 'success',
        })
        await this.$router.push('/product/productList')
      })
    },
    onCancel() {
      this.$router.push('/product/productList')
    },
  },
}
</script>

<style>
.box-card {
  width: 60%;
  margin: auto;
}
.title {
  text-align: center;
  margin-bottom: 40px;
  font-size: 40px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
